package com.uinnova.product.eam;

import com.binary.core.exception.BinaryException;
import com.binary.core.exception.MessageException;
import com.uinnova.product.eam.base.cj.ResultMsg;
import com.uinnova.product.eam.base.enums.ResultCodeEnum;
import com.uinnova.product.eam.service.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 全局异常处理
 * @author: Lc
 * @create: 2021-12-09 17:45
 */
@RestControllerAdvice(basePackages = "com.uinnova.product.eam.web.cj")
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResultMsg businessHandlerException(BusinessException e) {
        logger.error(e.getMessage(), e);
        return new ResultMsg(false, e.getCode(), e.getMessage(),e.getData());
    }

    @ExceptionHandler({ArithmeticException.class, NullPointerException.class})
    public ResultMsg runtimeExceptionException(Exception e) {
        logger.error(e.getMessage(), e);
        return new ResultMsg(false, ResultCodeEnum.SERVICE_ERROR.getCode(), ResultCodeEnum.SERVICE_ERROR.getMessage());
    }

    @ExceptionHandler({MessageException.class})
    public void messageExceptionErrorHandler(HttpServletRequest req, Exception e) {
        logger.error(e.getMessage(), e);
        if(e.getMessage().contains("Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]")){
            throw new BinaryException("对应索引尚未初始化,请稍后再试");
        }
        throw new BinaryException(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultMsg handler(MethodArgumentNotValidException e) {
        List<String> errors = e.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return ResultMsg.error(ResultCodeEnum.PARAMS_ERROR.getCode(), StringUtils.join(errors, ","));
    }

}
